package com.liebaut.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Adds CORS headers to requests to enable cross-site AJAX calls.
 */
public class CorsFilter implements Filter {

    private String regex;
    
    public void init(FilterConfig cfg) throws ServletException {
        regex = cfg.getInitParameter("allow.origin.regex");
        if (regex == null) {
        	regex = "*";
        }
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {
        if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) {
        	HttpServletRequest request = (HttpServletRequest) req;
        	HttpServletResponse response = (HttpServletResponse) res;
        	
        	if(request.getHeader("Origin") != null){
				String allowedOrigin = request.getHeader("Origin");
				boolean match = false;
				if(!regex.equals("*")){
					Pattern pattern = Pattern.compile(regex);
					Matcher matcher = pattern.matcher(allowedOrigin);
					match = matcher.matches();
				} else {
					match = true;
				}
				
				if(match){
					response.setHeader("Access-Control-Allow-Origin", allowedOrigin);
					response.setHeader("Access-Control-Allow-Credentials", "true");
					response.setHeader("Access-Control-Expose-Headers", "link");
					
					if ("OPTIONS".equals(request.getMethod())) {
						response.setHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
						response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
						response.setHeader("Access-Control-Max-Age", "3600");
					}
				}
			}
        }
        filterChain.doFilter(req, res);
    }

    public void destroy() {
    }
}


